import { createContext, useContext, useMemo, useState } from 'react'
import { Redirect } from 'react-router-dom'
import { useHistory } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
import { NavLink } from 'react-router-dom'
import { Route } from 'react-router-dom'
import { Switch } from 'react-router-dom'

const api = {
  login() {
    return fetch('https://randomuser.me/api')
      .then((resp) => resp.json())
      .then((json) => json.results[0].login)
  },
  logout() {
    return new Promise((resolve) => setTimeout(resolve, 100))
  },
}

const UserContext = createContext()
const UserContextProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const contextValue = useMemo(() => ({user, setUser}), [user])

  return <UserContext.Provider value={contextValue}>
      {children}
    </UserContext.Provider>
}
const useUserContext = () => useContext(UserContext)

const Public = () => <h2>公共页面</h2>
const Login = () => {
  const {setUser} = useUserContext()
  const location = useLocation()
  const history = useHistory()
  console.log('login location', location)
  return <>
    <h2>登录</h2>
    <button onClick={() => {
        api.login().then(user => {
          setUser(user)
          history.push(
            location?.state?.from || '/auth/pub'
          )
        })
      }}>登录</button>
  </>
}
const MyPage = () => {
  const {user, setUser} = useUserContext()
  const history=useHistory()
  return <>
    <h2>我的页面</h2>
    <p>你好，{user && user.username}</p>
    <button onClick={() => {
      api.logout().then(() => {
        setUser(null)
        history.push('/auth/login')
      })
    }}>登出</button>
  </>
}
const MyPage2 = () => <h2>我的第二个私密页面</h2>

const MyRoute = (props) => {
  const {user} = useUserContext()
  const location = useLocation()
  // console.log(location);
  return user ? <Route {...props} /> :
                <Redirect to={{
                  pathname: "/auth/login",
                  state: {from: location}
                }} />
}

const AuthDemo = () => {
  return (
    <UserContextProvider>
      <h1>自动智能路由</h1>
      <NavLink
        to="/auth/pub"
        style={(isActive) => ({
          textDecoration: isActive ? 'none' : 'underline',
        })}
      >
        公开页面
      </NavLink>{' '}
      <NavLink
        to="/auth/login"
        style={(isActive) => ({
          textDecoration: isActive ? 'none' : 'underline',
        })}
      >
        登录
      </NavLink>{' '}
      <NavLink
        to="/auth/my"
        style={(isActive) => ({
          textDecoration: isActive ? 'none' : 'underline',
        })}
      >
        我的页面
      </NavLink>{' '}
      <NavLink
        to="/auth/my2"
        style={(isActive) => ({
          textDecoration: isActive ? 'none' : 'underline',
        })}
      >
        我的页面2
      </NavLink>
      <Switch>
        <Route path="/auth/pub" component={Public} />
        <Route path="/auth/login" component={Login} />
        <MyRoute path="/auth/my" component={MyPage} />
        <MyRoute path="/auth/my2" component={MyPage2} />
      </Switch>
    </UserContextProvider>
  )
}

export default AuthDemo
